from datetime import timedelta
from tools.datetime import as_datetime
from zmad.models import ZTPResource


def date_eq(field, date):
    """生成日期查询语句"""
    dt_begin = as_datetime(date)
    dt_end = dt_begin + timedelta(days=1)
    return {field: {'$gte': dt_begin, '$lt': dt_end}}


def date_range(field, date_from=None, date_to=None):
    """生成日期范围查询语句"""
    query = {}
    if date_from or date_to:
        query[field] = {}
        if date_from:
            query[field]['$gte'] = as_datetime(date_from)
        if date_to:
            query[field]['$lt'] = as_datetime(date_to) + timedelta(days=1)
    return query


def res_queryset_id2name(queryset, id_field='_id'):
    """CAS日志中的resource是资源id，需要翻译为资源名称"""
    res_mapping = dict(ZTPResource.objects.values_list('pk', 'name'))
    queryset_in_mapping = []
    for agg in queryset:
        if agg.get(id_field) in res_mapping:
            agg[id_field] = res_mapping[agg.get(id_field)]
            queryset_in_mapping.append(agg)
    return queryset_in_mapping


def res_queryset_id2name_new(queryset, resource,id_field='_id'):
    """CAS日志中的resource是资源id，需要翻译为资源名称"""
    res_mapping = dict(ZTPResource.objects.values_list('pk', 'name'))
    # print(28, res_mapping)
    queryset_in_mapping = []
    for agg in queryset:
        if resource in res_mapping:
            platform = agg[id_field]
            agg[id_field] = res_mapping[resource]
            agg["platform"] = platform
            queryset_in_mapping.append(agg)
    return queryset_in_mapping